import { baseMapConfig, PropData, productorIP } from "../map/mapconfig";
import axios from "axios";
import { loadCss } from "esri-loader";
let index = -1;
let s_x = "";
let s_y = "";
let s_e = {};
let s_resData = [];
let s_finalObj = {};
let s_indexMapArr = [];
//添加一个图层
function addFeatureLayer(id) {
  // window[id].visible = true;
  window["esri"].mapAdd(id);
}
//移除一个图层
function removeFeatureLayer(id) {
  // window[id].visible = false;
  window["esri"].mapRemove(id);
}
//移除所有图层
export function removeAllLayers() {
  window["tree"].forEach(item => {
    removeFeatureLayer(item);
  });
}
//切换底图
export function switchBaseMap(id) {
  let baseMapUrl = "";
  baseMapConfig.forEach((item, index) => {
    if (index == id) {
      baseMapUrl = item.url;
    }
  });
  window["esri"].changeBaseMap(baseMapUrl);
}
//拿到选中的树形结构的id
export function changeImageLayer(id, flag) {
  if (!id && !flag) {
    //默认
    window["tree"] = [51, 31];
    window["tree"].forEach(item => {
      //添加图层
      addFeatureLayer(item);
    });
  } else {
    //复选狂点击事件
    if (flag) {
      //添加
      addFeatureLayer(id);
      window["tree"].push(id);
    } else {
      //取消
      let res = window["tree"].filter(item => item != id);
      window["tree"] = res;
      removeFeatureLayer(id);
    }
  }
}
//地图放大
export function mapZoomIn() {
  window["esri"].zoomIn();
}
//地图缩小
export function mapZoomOut() {
  window["esri"].zoomOut();
}
//视觉飞入
// export function mapGoTo(x, y, z = 32000) {
export function mapGoTo(x, y,zoom) {
  window["esri"].goTo(x, y,zoom);
}

function flat(arr) {
  let tmp = [];
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].length; j++) {
      tmp.push(arr[i][j]);
    }
  }
  return tmp;
}

export function getDataBaseMap(x, y, db, e, PuopName) {
  //拿到图层的id     eg:31
  let layerItem = window["tree"][window["tree"].length - 1];
  let first = String(layerItem).slice(0, 1);
  let last = String(layerItem).slice(1, 2);
  let nameStr = "";
  let arr1 = [
    { index: 1, str: "fdsj" },
    { index: 2, str: "hxsj" },
    { index: 3, str: "zxgh" },
    { index: 4, str: "kxgh" }
  ];
  //匹配本地数据表的第一层 -> 图层名
  arr1.forEach(item => {
    if (item.index == first) {
      nameStr = item.str;
    }
  });

  //匹配到本地数据表的第一层 -> 数据对象
  let localData = PropData[0];
  let tmpObj = {};
  for (let i in localData) {
    if (i == nameStr) {
      tmpObj = localData[i];
    }
  }

  //因为树形结构和本地数据表里面的数据顺序有出入，为了统一数据，做兼容处理
  let finalObj = {}; //##  点击的图层数据表里面的所有字段
  last =
    nameStr == "kxgh" && last == 1
      ? 2
      : nameStr == "kxgh" && last == 2
      ? 1
      : last;
  for (let index in tmpObj) {
    if (index == last - 1) {
      finalObj = tmpObj[index];
    }
  }
  let _this = this;

  axios({
    method: "GET",
    url: `${productorIP}/cnplan/getGis?x=${x}&y=${y}&name=${db}` //线上
    // url: `api/cnplan/getGis?x=${x}&y=${y}&name=${db}` // 本地
  }).then(res => {
    let resData = flat(res.data);
    //分离数据和数据库名
    let arrValue = [];
    let arrKey = [];
    for (var i = 0; i < resData.length / 2; i++) {
      arrValue.push(resData[2 * i]);
      arrKey.push(resData[2 * i + 1]);
    }
    //无数据直接返回 CNKW@123 CNKWXXZX
    if (arrValue.length == 0) {
      return false;
    } 

    //数组每一项遍历，每项属性值键值对，改为数组形式
    console.log(arrValue);
    // arrValue = arrValue.map(item => {
    //   // let resItem = item.map((item2, index) => {
    //   let tmp = [];
    //   for (let i in item) {
    //     if (item[i]) {
    //       tmp.push({ name: i, value: item[i] });
    //     }
    //   }
    //   console.log(tmp);  
    //   return tmp;
    // });
    arrValue = arrValue.map(item => {
      let resItem = item.map((item2, index) => {
        let tmp = [];
        for (let i in item2) {
          if (item2[i]) {
            tmp.push({ name: i, value: item2[i] });
          }
        }
        return tmp;
      });
      return resItem;
    });
    console.log(arrValue);
    //name关联数据
    let indexMapArr = [];
    let myIndex = 0;
    for (let i = 0; i < arrValue.length; i++) {
      for (let j = 0; j < arrValue[i].length; j++) {
        indexMapArr.push({ index: myIndex, name: arrKey[i] });
        myIndex++;
      }
    }
    index = -1;
    s_x = x;
    s_y = y;
    s_e = e;

    s_resData = flat(arrValue);
    s_finalObj = finalObj;
    s_indexMapArr = indexMapArr;
    window["esri"].btnShow(s_resData.length);
    addPoup();
  });
}
//上一页
export function addPoup() {
  index++;
  if (index >= s_resData.length) {
    index = s_resData.length - 1;
    return false;
  }
  setUp();
}
//下一页
export function reduPoup() {
  index--;
  if (index < 0) {
    index = 0;
    return false;
  }
  setUp();
}
function setUp() {
  //先移除之前的高亮图层面
  view.graphics.remove(window["Area_Graphic"]);
  //取出临时变量
  let x = s_x;
  let y = s_y;
  let e = s_e;
  let resData = s_resData;
  let finalObj = s_finalObj;

  //兼容写法，geom存在取geom的值，不存在取geojson
  console.log(resData, "resData");
  let geomData = resData[index].filter(item => item.name == "geom");
  let geojsonData = resData[index].filter(item => item.name == "geojson");
  let points = geomData[0]
    ? JSON.parse(geomData[0].value).coordinates
    : geojsonData
    ? JSON.parse(geojsonData[0].value).coordinates
    : [];

  //将请求到的数据值和本地的字段名,融合成需要的新数组
  let strContent = "";
  let clearArr = []; //##弹框数据
  resData[index].forEach(item => {
    finalObj.fieldInfos.forEach(item2 => {
      if (item.name == item2.fieldName) {
        clearArr.push({ name: item2.label, value: item.value });
      }
    });
  });

  //取出表名
  let tableName = "";
  let indexMapArr = s_indexMapArr;
  indexMapArr.forEach((item, indexT) => {
    if (index == item.index) {
      tableName = item.name;
    }
  });

  //弹框的样式

  let strStyle = `border-left: 1px solid #cbcbcb;
            border-width: 0 0 0 1px;
            font-size: inherit;
            margin: 0;
            overflow: visible;
            padding: .5em 1em;`;
  let headStyle = `border-collapse: collapse;
    width:100%;
    border-spacing: 0;
    empty-cells: show;
    border: 1px solid #cbcbcb; border-collapse: collapse;
    border-spacing: 0;`;
  let active = `background:#f2f2f2;`;
  let localAddress = `${productorIP}/cnplan/arc_file/index?featureType=zh&arcNumsel=`;
  // console.log(localAddress);
  let userName = localStorage.getItem('username')
  // console.log(userName);
  //循环拼接表单
  clearArr.forEach((item, index) => {
    console.log(item);
    if (item.name == "图形档号") {
      // console.log(`${localAddress}${item.value}`);
      strContent += ` <tr>
                <td style="${strStyle}${index % 2 == 0 ? active : ""}"><b>${
        item.name
      }</b></td>
                <td style="${strStyle}${
        index % 2 == 0 ? active : ""
      }"><a ${userName == 'user' ? '' : 'href=' + localAddress + item.value}  target='_blank'>${
        item.value
      }</a></td>
            
            </tr>`;
    } else {
      strContent += ` <tr>
                <td style="${strStyle}${index % 2 == 0 ? active : ""}"><b>${
        item.name
      }</b></td>
                <td style="${strStyle}${index % 2 == 0 ? active : ""}">${
        item.value
      }</td>
            
            </tr>`;
    }
  });
  let strHead = `<table style="${headStyle}">
        <tbody id="body">`;
  let strFooter = `</tbody></table>`;
  let porpTableName = `当前图层:${tableName}`;
  let porpTablePage = `<div><b>当前第${index + 1}页/共${
    s_resData.length
  }页</b></div>`;

  //图层高亮
  var polyline = {
    type: "polygon",
    rings: points,
    spatialReference: {
      wkid: 3857
    }
  };
  var fillSymbol = {
    type: "simple-fill",
    color: [252, 255, 255, 0.1],
    // color: [255, 255, 255],
    outline: {
      // color: [0, 255, 255],
      color: "#51ffff",
      width: 2
    }
  };

  var polylineGraphic = new Graphic({
    geometry: polyline,
    symbol: fillSymbol
  });
  window["Area_Graphic"] = polylineGraphic;
  view.graphics.add(polylineGraphic);

  //弹框提示
  view.popup.open({
    title: porpTableName,
    location: e.mapPoint,
    content: porpTablePage + strHead + strContent + strFooter
  });
  view.popup.dockEnabled = true;
  // view.popup.autoCloseEnabled = false;

  //视角定位
  mapGoTo(x, y,13);
}
